package com.shajj.data.rss;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;
import com.shajj.data.DataManager;
import com.shajj.data.PMF;
import com.shajj.data.RssRecord;
import com.shajj.data.SerializableList;

public class RssRecordDataManager implements DataManager<RssRecord> {
	private PersistenceManager persistenceManager;
	private Query singleQuery;
	private Query pageQuery;

	private Cache cache;

	private static RssRecordDataManager instance = new RssRecordDataManager();

	public static RssRecordDataManager getInstance() {
		return instance;
	}

	public RssRecordDataManager() {
		persistenceManager = PMF.get().getPersistenceManager();
		singleQuery = persistenceManager.newQuery(RssRecord.class, "id == idParam");
		singleQuery.declareParameters("Long idParam");
		pageQuery = persistenceManager.newQuery(RssRecord.class);
		try {
			Map<Integer, Integer> props = new HashMap<Integer, Integer>();
			props.put(GCacheFactory.EXPIRATION_DELTA, 5 * 60);
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(props);
		} catch (CacheException e) {
		}
	}

	@SuppressWarnings("unchecked")
	public RssRecord get(Long id) {
		List<RssRecord> list = (List<RssRecord>) singleQuery.execute(id);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<RssRecord> getByCache(int start, int size) {
		String key = String.valueOf(start) + "_" + String.valueOf(size);
		Object records = cache.get("key");
		if (records == null) {
			records = getByPage(start, size);
			cache.put(key, records);
		}
		return (List<RssRecord>) records;
	}

	@SuppressWarnings("unchecked")
	public List<RssRecord> getByPage(int start, int size) {
		pageQuery.setRange(start, start + size);
		pageQuery.setOrdering("time desc");
		return new SerializableList<RssRecord>((List<RssRecord>) pageQuery.execute());
	}

	@Override
	public void save(RssRecord rssRecord) {
		persistenceManager.makePersistent(rssRecord);
	}

	@Override
	public List<RssRecord> search(String queryString) {
		return RssSearchJanitor.search(queryString, persistenceManager);
	}
}
